package com.springsource.boot.run;

import org.springframework.boot.DefaultBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.RandomValuePropertySourceEnvironmentPostProcessor;
import org.springframework.boot.logging.DeferredLog;
import org.springframework.boot.logging.DeferredLogs;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.support.SpringFactoriesLoader;

import java.util.List;

public class Step5 {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication();
        StandardEnvironment env = new StandardEnvironment();

        System.out.println(">>>>>>>>>>>>>>增强之前");
        for (PropertySource<?> propertySource : env.getPropertySources()) {
            System.out.println(propertySource);
        }
        // 增强之后多了一个OriginTrackedMapPropertySource，处理了application.yml/properties的配置文件
        ConfigDataEnvironmentPostProcessor configDataEnvironmentPostProcessor = new ConfigDataEnvironmentPostProcessor(new DeferredLogs(), new DefaultBootstrapContext());
        configDataEnvironmentPostProcessor.postProcessEnvironment(env, app);
        // 增强之后多了一个RandomValuePropertySource，可以获取随机数
        RandomValuePropertySourceEnvironmentPostProcessor randomValuePropertySourceEnvironmentPostProcessor = new RandomValuePropertySourceEnvironmentPostProcessor(new DeferredLog());
        randomValuePropertySourceEnvironmentPostProcessor.postProcessEnvironment(env, app);

        // 具体使用了哪些EnvironmentPostProcessor实现类，是写在spring.factories的配置文件中
        List<String> names = SpringFactoriesLoader.loadFactoryNames(EnvironmentPostProcessor.class, Step5.class.getClassLoader());
        for (String name : names) {
            System.out.println(name);
        }
        // 是谁在什么时机来调用这些EnvironmentPostProcessor实现类呢？
        // EnvironmentPostProcessorApplicationListener监听器
        // 事件来自于Step4中发布的EventPublishingRunListener.environmentPrepared事件

        System.out.println(">>>>>>>>>>>>>>增强之后");

        for (PropertySource<?> propertySource : env.getPropertySources()) {
            System.out.println(propertySource);
        }


        // 获取随机数
        System.out.println(env.getProperty("random.int"));
        // 获取uuid
        System.out.println(env.getProperty("random.uuid"));

    }

}
